import $store from "@//store";
import { VUE_APP_WS_URL, VUE_APP_RESOURCES_URL } from "@/config";

const Socket = function() {
	this.timer = '';
	this.heartbeatFailNum = 0;
	this.socketTask = null;
	this.is_open_socket = false;
};
let data = []

Socket.prototype = {
  onOpen: function() {
    this.init();
  },
  init: function() {
	  var that=this;
    // 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
    this.socketTask = uni.connectSocket({
		url: VUE_APP_WS_URL+"/sy/socket/app/"+$store.state.token,
		header: {
		　　'content-type': 'application/json'
		},
		success(data) {
			console.log("连接成功");
		},
    });
    this.socketTask.onOpen((res) => {
      that.is_open_socket = true; 	
      this.socketTask.onMessage((res) => {
        // console.log("收到服务器内容：" + res.data);
        var state = res.data;
        if (state.indexOf("order") != -1) {
    		const innerAudioContext = uni.createInnerAudioContext();
    		innerAudioContext.autoplay = true;
    		innerAudioContext.src = VUE_APP_RESOURCES_URL+'/music/order.mp3';
    		innerAudioContext.onPlay(() => {
    		  console.log('开始播放');
    		});
    		innerAudioContext.onError((res) => {
    		  console.log(res.errCode+":"+res.errMsg);
    		});
    	}
		this.data = res.data
		Socket.data = res.data
      })
    })
    // 这里仅是事件监听【如果socket关闭了会执行】
    this.socketTask.onClose(() => {
      console.log("已经被关闭了")
    })  
    this.heartCheck();//开启心跳机制
  },
  closeSocket: function() {
	var that=this;
	clearInterval(this.timer);
    this.socketTask.close({
      success(res) {
        that.is_open_socket = false;
        console.log("关闭成功", res)
      },
      fail(err) {
        console.log("关闭失败", err)
      }
    })
  },
  heartCheck: function() {
    clearInterval(this.timer);
    var that=this;
    this.timer = setInterval(function() {
      //发送信息
      uni.sendSocketMessage({
        data: 'ping',
        success: res => {
          console.log("心跳发送成功");
          that.heartbeatFailNum = 0;
        },fail: err => {
          console.log("心跳发送失败");
          that.heartbeatFailNum + 1;
          if (that.heartbeatFailNum <= 10) {
            that.closeSocket();
            that.init();
          } else {
            console.log("连续十次心跳检测失败，不再发起重连请求")
          }
        }
      });
    }, 1000 * 30);
  },
  send: function(data) {
    
  },
  onMessage: function(res) {
	  
  },
  onError: function(e) {
    
  },
};

Socket.prototype.constructor = Socket;

export default Socket;
